// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import EventMgr from "./EventMgr";

const {ccclass, property} = cc._decorator;


var State = {
    Disconnected: 0, // 断开连接
    Connecting: 1, // 正在连接
    Connected: 2, // 已经连接;
};


export default class NetManager extends cc.Component {

    private static Instance: NetManager = null;;

    private state:any = State.Disconnected;

    private sock:WebSocket = null;


    private url: string = "ws://127.0.0.1:6081/ws";

    onLoad () 
    {

        if(NetManager.Instance == null)
        {
            NetManager.Instance = this;
        }else
        {

        }

    }


    public static getInstace()
    {
        return NetManager.Instance;
    }


    // 发起连接;
    connect_to_server() 
    {
        if (this.state !== State.Disconnected) 
        {

            return;
        }

        // EventMgr.Instance.dispatch_event("net_connecting", null);

        this.state = State.Connecting;
        this.sock = new WebSocket(this.url); // H5标准，底层做好了;
        this.sock.binaryType = "arraybuffer";
        this.sock.onopen = this._on_opened.bind(this);
        this.sock.onmessage = this._on_recv_data.bind(this);
        this.sock.onclose = this._on_socket_close.bind(this);
        this.sock.onerror = this._on_socket_err.bind(this);
    }

    private _on_opened(event) 
    {
        this.state = State.Connected;
        cc.log("connect to server: " + this.url + " sucess!");
        EventMgr.Instance.dispatch_event("net_connect", null);
    }

    private _on_recv_data(event) {
        EventMgr.Instance.dispatch_event("net_message", event.data);
    }

    private _on_socket_close()
    {
        this.close_socket();
    }


    private _on_socket_err(event) 
    {
        this.close_socket();
    }

    close_socket() 
    {
        if (this.state === State.Connected) 
        {
            if (this.sock !== null) 
            {
                this.sock.close();
                this.sock = null;
            }
        }
        // EventMgr.Instance.dispatch_event("net_disconnect", null);
        this.state = State.Disconnected;
    }


    // update (dt) {}
}
